package com.ias.business.testbiz.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import javax.sql.DataSource;
import java.nio.charset.StandardCharsets;

/**
 * 数据库初始化器
 * 应用启动时自动执行SQL初始化脚本
 * 
 * @author IAS Team
 * @since 1.0.0
 */
@Slf4j
@Component
public class DatabaseInitializer implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Override
    public void run(String... args) throws Exception {
        try {
            log.info("开始初始化数据库...");
            
            // 读取SQL脚本
            ClassPathResource resource = new ClassPathResource("sql/init.sql");
            byte[] sqlBytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
            String sql = new String(sqlBytes, StandardCharsets.UTF_8);
            
            // 执行SQL脚本
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            
            // 分割SQL语句并执行
            String[] sqlStatements = sql.split(";");
            for (String statement : sqlStatements) {
                String trimmedStatement = statement.trim();
                if (!trimmedStatement.isEmpty() && !trimmedStatement.startsWith("--")) {
                    try {
                        jdbcTemplate.execute(trimmedStatement);
                    } catch (Exception e) {
                        // 忽略已存在的错误，继续执行
                        if (!e.getMessage().contains("already exists")) {
                            log.warn("执行SQL语句时出现警告: {}", e.getMessage());
                        }
                    }
                }
            }
            
            log.info("数据库初始化完成！");
            
        } catch (Exception e) {
            log.error("数据库初始化失败", e);
        }
    }
} 